﻿
Public Class Users
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If AuthenticationValidator.CheckIfAuthorized(Me, "Users - View") = False Then
            Me.Response.Redirect("AccessDeniedMsg.aspx")
        End If

        If Me.IsPostBack = False Then
            RefreshUsers()
            toggleButtonStates()
        End If


    End Sub

    Private Sub toggleButtonStates()

        'default
        Add_Button.Enabled = False
        Save_Button.Enabled = False
        Delete_Button.Enabled = False

        'after authentication
        If Me.ViewState("SelectedUserId") Is Nothing Then
            If AuthenticationValidator.CheckIfAuthorized(Me, "Users - Add") Then Add_Button.Enabled = True
            Save_Button.Enabled = False
            Delete_Button.Enabled = False
        Else
            If AuthenticationValidator.CheckIfAuthorized(Me, "Users - Add") Then Add_Button.Enabled = True
            If AuthenticationValidator.CheckIfAuthorized(Me, "Users - Edit") Then Save_Button.Enabled = True
            If AuthenticationValidator.CheckIfAuthorized(Me, "Users - Delete") Then Delete_Button.Enabled = True
        End If
        If (AuthenticationValidator.CheckIfAuthorized(Me, "Users - Add") = False) _
            OrElse (AuthenticationValidator.CheckIfAuthorized(Me, "Users - Edit") = False) _
            OrElse (AuthenticationValidator.CheckIfAuthorized(Me, "Users - Delete") = False) Then
            info_Label.Text = "Some functionality of this screen, has been disabled, because you don't have sufficient rights. <br/>If you feel that this is an error, please contact the administrator of this system."
        Else
            If info_Label.Text = "Some functionality of this screen, has been disabled, because you don't have sufficient rights. <br/>If you feel that this is an error, please contact the administrator of this system." Then
                info_Label.Text = ""
            End If
        End If

    End Sub

    Private Sub RefreshUsers()

        Dim d As New DBHelper
        Users_ListBox.DataSource = d.GetUsersList
        Users_ListBox.DataTextField = "Text"
        Users_ListBox.DataValueField = "UserId"
        Users_ListBox.DataBind()

    End Sub

    Private Sub Users_ListBox_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles Users_ListBox.SelectedIndexChanged
        SelectUser(Users_ListBox.SelectedItem)
        toggleButtonStates()
        info_Label.Text = ""
    End Sub

    Private Sub SelectUser(item As ListItem)

        Dim userid As Guid
        If (item IsNot Nothing) _
            AndAlso (item.Value <> "") Then
            userid = New Guid(item.Value)
        Else
            userid = Nothing
        End If
        If userid = Guid.Empty Then
            Me.ViewState("SelectedUserId") = Nothing
            username_TextBox.Text = ""
            refreshSelectedUserProperties()
        Else
            Me.ViewState("SelectedUserId") = userid
            refreshSelectedUserProperties()
        End If

    End Sub

    Private Sub refreshSelectedUserProperties()

        If (Me.ViewState("SelectedUserId") IsNot Nothing) _
            AndAlso (CType(Me.ViewState("SelectedUserId"), Guid) <> Guid.Empty) Then
            Dim d As New DBHelper
            Dim uid As Guid = Me.ViewState("SelectedUserId")
            Dim user As UserType = d.GetUserById(uid)
            username_TextBox.Text = user.UserName
            For Each item As ListItem In Rights_CheckBoxList.Items
                item.Selected = False
                For Each r As String In user.Rights
                    If item.Text.ToLower = r.ToLower Then
                        item.Selected = True
                        Exit For
                    End If
                Next
            Next
        Else
            username_TextBox.Text = ""
            For Each item As ListItem In Rights_CheckBoxList.Items
                item.Selected = False
            Next
        End If

    End Sub

    Protected Sub Add_Button_Click(sender As Object, e As EventArgs) Handles Add_Button.Click

        Dim db As New DBHelper
        Dim user As New UserType
        user.UserName = username_TextBox.Text
        For Each item As ListItem In Rights_CheckBoxList.Items
            If item.Selected Then
                user.Rights.Add(item.Text)
            End If
        Next
        Try
            db.AddUser(user)
            RefreshUsers()
            info_Label.Text = ""
        Catch ex As SqlClient.SqlException
            If ex.Message.Contains("unique index") Then
                info_Label.Text = "User name already exists in the system, cannot insert duplicate usernames"
            Else
                info_Label.Text = ex.Message
            End If
        Catch ex As Exception
            info_Label.Text = ex.Message
        End Try

    End Sub

    Protected Sub Save_Button_Click(sender As Object, e As EventArgs) Handles Save_Button.Click

        Dim db As New DBHelper
        Dim uid As Guid = Me.ViewState("SelectedUserId")
        Dim user As UserType = db.GetUserById(uid)
        user.UserName = username_TextBox.Text
        user.Rights.Clear()
        For Each item As ListItem In Rights_CheckBoxList.Items
            If item.Selected Then
                user.Rights.Add(item.Text)
            End If
        Next
        Try
            db.UpdateUser(user)
            RefreshUsers()

            If user.UserId.Equals(AuthenticationValidator.GetLoggedInUser(Me).UserId) Then
                info_Label.Text = "You have edited the current logged in user, to apply the new access rights, you will have to login again.."
                Dim meta As New HtmlMeta
                meta.HttpEquiv = "Refresh"
                meta.Content = "3; URL=Login.aspx"
                Me.Page.Header.Controls.Add(meta)
            Else
                info_Label.Text = ""
            End If
        Catch ex As SqlClient.SqlException
            If ex.Message.Contains("unique index") Then
                info_Label.Text = "User name already exists in the system, cannot insert duplicate usernames"
            Else
                info_Label.Text = ex.Message
            End If
        Catch ex As Exception
            info_Label.Text = ex.Message
        End Try

    End Sub

    Protected Sub Delete_Button_Click(sender As Object, e As EventArgs) Handles Delete_Button.Click

        Dim db As New DBHelper
        Dim uid As Guid = Me.ViewState("SelectedUserId")
        Dim user As New UserType(uid)
        Try
            db.DeleteUser(user)
            selectUser(Nothing)
            RefreshUsers()
            If user.UserId.Equals(AuthenticationValidator.GetLoggedInUser(Me).UserId) Then
                info_Label.Text = "You have edited the current logged in user, to apply the new access rights, you will be logged off for now in 5 secs"
                Dim meta As New HtmlMeta
                meta.HttpEquiv = "Refresh"
                meta.Content = "5; URL=Login.aspx"
                Me.Page.Header.Controls.Add(meta)
            Else
                info_Label.Text = ""
            End If
        Catch ex As Exception
            info_Label.Text = ex.Message
        End Try

    End Sub

End Class